using System;
using System.Threading;

namespace TXK.CommonBase
{
	/// <summary>
	/// 一个简单的混合线程同步锁，采用了基元用户加基元内核同步构造实现
	/// 具体见CLR一书
	/// </summary>
	public sealed class SimpleLock : IDisposable
	{
		private bool disposedValue = false;

		/// <summary>
		/// 基元用户模式构造同步锁
		/// </summary>
		private int m_waiters = 0;

		/// <summary>
		/// 基元内核模式构造同步锁
		/// </summary>
		private AutoResetEvent m_waiterLock = new AutoResetEvent(initialState: false);

		/// <summary>
		/// 获取当前锁是否在等待当中
		/// </summary>
		public bool IsWaitting => this.m_waiters == 0;

		private void Dispose(bool disposing)
		{
			if (!this.disposedValue)
			{
				if (disposing)
				{
				}
				this.m_waiterLock.Close();
				this.disposedValue = true;
			}
		}

		/// <summary>
		/// 释放资源
		/// </summary>
		public void Dispose()
		{
			this.Dispose(disposing: true);
		}

		/// <summary>
		/// 获取锁
		/// </summary>
		public void Enter()
		{
			if (Interlocked.Increment(ref this.m_waiters) != 1)
			{
				this.m_waiterLock.WaitOne();
			}
		}

		/// <summary>
		/// 离开锁
		/// </summary>
		public void Leave()
		{
			if (Interlocked.Decrement(ref this.m_waiters) != 0)
			{
				this.m_waiterLock.Set();
			}
		}
	}
}
